'use client';

import type { IPagination, IPost, IQueryParams } from '@/interfaces';
import { queryAllPost, searchPost } from '@/services/api';
import { type ChangeEvent, useContext, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import classNames from 'classnames';
import { useRouter, useSearchParams } from 'next/navigation';
import {
  POST_OTHER_STATE_KEY,
  POST_REVIEW_STATE_KEY,
  POST_SORT_STATE_KEY,
} from '@/lib/constant';
import useToast from '@/hooks/useToast';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import { PostAdminContext } from '@/contexts/admin/forum/post';
import { formatDate } from '@/lib/tool';
import UpdatePostAdminPage from '@/app/[locale]/admin/forum/post/update';
import DetailsPostAdminPage from '@/app/[locale]/admin/forum/post/detail';
import PostName from '@/app/[locale]/common/post/name';

export default function ListPostAdminPage(this: any) {
  const { show } = useToast();
  const [currentItemId, setCurrentItemId] = useState<number>();
  const urlSearchParams = useSearchParams();
  const [params, setParams] = useState<IQueryParams>({
    page: urlSearchParams?.has('page')
      ? parseInt(urlSearchParams.get('page') + '')
      : 0,
    sectionId: urlSearchParams?.has('sid')
      ? parseInt(urlSearchParams.get('sid') + '')
      : undefined,
  });
  const [searchName, setSearchName] = useState('');
  const queryKey = ['/forum', '/posts', params, searchName];
  const [isCreate, setIsCreate] = useState(false);
  const [detailItem, setDetailItem] = useState<IPost>();
  const [updateItem, setUpdateItem] = useState<IPost>();
  const context = useContext(PostAdminContext);
  const router = useRouter();

  const queryAllPostQuery = useQuery(
    queryKey,
    async (context) => {
      if (searchName) {
        return (await searchPost({
          query: {
            ...(context.queryKey[2] as any),
            name: context.queryKey[3],
          },
        })) as IPagination<IPost>;
      } else {
        return (await queryAllPost({
          query: context.queryKey[2] as any,
        })) as IPagination<IPost>;
      }
    },
    {
      keepPreviousData: true,
    },
  );

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value;
    setSearchName(value.toLowerCase() || '');
  }

  async function onClickCreate() {
    await router.push('/posts/new');
  }

  function onClickDetail(item: IPost) {
    setDetailItem(item);
    setCurrentItemId(item.id);
  }

  function onClickUpdate(item: IPost) {
    setUpdateItem(item);
  }

  function onClickPrevious() {
    const data = queryAllPostQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryAllPostQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  if (queryAllPostQuery.data) {
    const data = queryAllPostQuery.data;

    return (
      <PostAdminContext.Provider
        value={{
          ...context,
          isCreate,
          detailItem,
          updateItem,
          setIsCreate,
          setDetailItem,
          setUpdateItem,
          queryKey,
        }}
      >
        <div className="row">
          <div className="col">
            <div className="vstack gap-4">
              <div className="row">
                <div className="col">
                  <div className="card">
                    <div className="card-header bg-transparent">
                      <div className="row row-cols-auto justify-content-between g-2">
                        <div className="col">
                          <div className="input-group">
                            <span className="input-group-text">
                              <i className="bi bi-search"></i>
                            </span>
                            <input
                              onChange={onChangeSearch}
                              type="search"
                              className="form-control"
                              placeholder="搜索帖子"
                            />
                          </div>
                        </div>
                        <div className="col">
                          <div className="hstack gap-3">
                            <button
                              onClick={onClickCreate}
                              type="button"
                              className="btn btn-primary"
                            >
                              <i className="bi bi-plus-lg me-2"></i>
                              新增帖子
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="card-body">
                      <div className="table-responsive">
                        <table className="table table-hover align-middle">
                          <thead>
                            <tr className="text-nowrap">
                              <th scope="col" className="w-10">
                                ID
                              </th>
                              <th scope="col" className="w-10">
                                名称
                              </th>
                              <th scope="col" className="w-10">
                                审核
                              </th>
                              <th scope="col" className="w-10">
                                其他状态
                              </th>
                              <th scope="col" className="w-10">
                                排序
                              </th>
                              <th scope="col" className="w-10">
                                作者
                              </th>
                              <th scope="col" className="w-10">
                                更新
                              </th>
                              <th scope="col" className="w-10"></th>
                            </tr>
                          </thead>
                          <tbody>
                            {data.content.map((item) => {
                              return (
                                <tr
                                  key={item.id}
                                  className={classNames('text-nowrap', {
                                    'table-active': currentItemId === item.id,
                                  })}
                                >
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.id}
                                  </td>
                                  <td className="text-truncate">
                                    <PostName
                                      item={item}
                                      isTable
                                      isFwSemibold={false}
                                    />
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {
                                      POST_REVIEW_STATE_KEY[
                                        item.details!.reviewState
                                      ]
                                    }
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {(item.details!.otherStates.length === 0
                                      ? ['DEFAULT']
                                      : item.details!.otherStates
                                    )
                                      .map(
                                        (value) => POST_OTHER_STATE_KEY[value],
                                      )
                                      .join(',')}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {
                                      POST_SORT_STATE_KEY[
                                        item.details!.sortState
                                      ]
                                    }
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.creatorAlias}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {formatDate(item.contentUpdatedOn)}
                                  </td>
                                  <td>
                                    <button
                                      onClick={onClickUpdate.bind(this, item)}
                                      className="btn btn-sm btn-light me-2"
                                      type="button"
                                    >
                                      <i className="bi bi-pencil me-2"></i>
                                      修改
                                    </button>
                                  </td>
                                </tr>
                              );
                            })}
                          </tbody>
                        </table>

                        {data.content.length === 0 && (
                          <Alert message="暂无帖子" />
                        )}

                        <div className="my-4">
                          <nav aria-label="版块分页">
                            <ul className="pagination justify-content-end">
                              <li
                                className={classNames(
                                  'page-item',
                                  data.pageable.previous ? false : 'disabled',
                                )}
                              >
                                <a
                                  onClick={onClickPrevious}
                                  className="page-link cursor-pointer"
                                >
                                  上一页
                                </a>
                              </li>
                              <li
                                className={classNames(
                                  'page-item',
                                  data.pageable.next ? false : 'disabled',
                                )}
                              >
                                <a
                                  onClick={onClickNext}
                                  className="page-link cursor-pointer"
                                >
                                  下一页
                                </a>
                              </li>
                            </ul>
                          </nav>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {detailItem && <DetailsPostAdminPage />}

              {updateItem && <UpdatePostAdminPage />}
            </div>
          </div>
        </div>
      </PostAdminContext.Provider>
    );
  }

  if (queryAllPostQuery.error) {
    return <Alert message={queryAllPostQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
